package com.zmn.oms.dubbo.impl.zmn.factory.order;

import com.zmn.oms.business.interfaces.es.OrderWorkEsBService;
import org.apache.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.oms.business.impl.base.AbstractListEsQueryServiceImpl;
import com.zmn.oms.dubbo.dto.zmn.order.factory.FcOrderCount;
import com.zmn.oms.dubbo.interfaces.zmn.factory.order.FactoryOrderListRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;

import java.util.*;

/**
 * @author sunlife
 * @date 2019/5/22 18:55
 */
@Service(loadbalance = "roundrobin", timeout = 5000, retries = 2, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class FactoryOrderListRemoteServiceImpl extends AbstractListEsQueryServiceImpl implements FactoryOrderListRemoteService {

    private static final Logger logger = LoggerFactory.getLogger(FactoryOrderListRemoteServiceImpl.class);

    @Autowired
    OrderWorkEsBService orderWorkEsBService;

    /**
     * 工单状态
     */
    private String queryFieldOrderStatus = "status";
    /**
     * 结果状态
     */
    private String queryFieldResultStatus = "resultStatus";
    /**
     * 接单时间/录入时间
     */
    private String queryFieldReciveTime = "receiveTime";
    /**
     * 评价星数
     */
    private String queryFieldComment = "commentScore";
    /**
     * 评价时间
     */
    private String queryFieldCommentTime = "commentTime";

    @Override
    public ResponseDTO<FcOrderCount> queryFactoryOrderOverview(Integer factoryId) {

        logger.info("言而有信厂商订单统计：{}", factoryId);

        OrderWorkQuery orderWorkQuery = new OrderWorkQuery();
        orderWorkQuery.setPlat(GlobalConsts.PLAT_MARK_YEYX);
        orderWorkQuery.setFactoryIdList(Lists.newArrayList(factoryId));
        orderWorkQuery.setPageSize(1);

        NativeSearchQuery searchQuery = super.builderSearchQuery(orderWorkQuery);

         
        //总订单数
        FilterAggregationBuilder allOrder = AggregationBuilders.filter("allOrder_filter", QueryBuilders.boolQuery());
        // 总计完成
//        FilterAggregationBuilder allCompleteOrder = AggregationBuilders.filter("allCompleteOrder_filter", QueryBuilders.boolQuery()
//                .must(QueryBuilders.termsQuery(queryFieldOrderStatus, Lists.newArrayList(OrderGlobalConsts.WORK_STATUS_COMPLETE, OrderGlobalConsts.WORK_STATUS_CHECKOUT, OrderGlobalConsts.WORK_STATUS_ACCOUNT)))
//        );
        // 剩余服务中
//        FilterAggregationBuilder allDoingOrder = AggregationBuilders.filter("allDoingOrder_filter", QueryBuilders.boolQuery()
//                .must(QueryBuilders.termQuery(queryFieldResultStatus, OrderGlobalConsts.WORK_RESULT_DOING))
//        );
        // 今日订单
        FilterAggregationBuilder todayOrder = AggregationBuilders.filter("todayOrder_filter", QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery(queryFieldReciveTime)
                        .from(DateUtil.getNowFormatted("yyyy-MM-dd"))
                        .includeLower(true).includeUpper(true))
        );
        // 本周订单
        Calendar cal = Calendar.getInstance();

        FilterAggregationBuilder weekOrder = AggregationBuilders.filter("weekOrder_filter", QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery(queryFieldReciveTime)
                        .from(DateUtil.dateFormatToString(DateUtil.getWeekStart(cal.get(Calendar.YEAR),cal.get(Calendar.WEEK_OF_YEAR)), DateUtil.FORMAT_DATE))
                        .to(DateUtil.getNowFormatted("yyyy-MM-dd"))
                        .includeLower(true).includeUpper(true))
        );
        // 本月订单
        FilterAggregationBuilder monthOrder = AggregationBuilders.filter("monthOrder_filter", QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery(queryFieldReciveTime)
                        .from(DateUtil.getMonthFirstDay(DateUtil.getNow()))
                        .to(DateUtil.getNowFormatted("yyyy-MM-dd"))
                        .includeLower(true).includeUpper(true))
        );
        // 好评
        FilterAggregationBuilder GoodComment = AggregationBuilders.filter("goodComment_filter", QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery(queryFieldComment, 5))
        );
        // 中评
        FilterAggregationBuilder middleComment = AggregationBuilders.filter("middleComment_filter", QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery(queryFieldComment, 4))
        );
        // 差评
        FilterAggregationBuilder badComment = AggregationBuilders.filter("badComment_filter", QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery("commentScore").lte(3))
        );

        searchQuery.addAggregation(allOrder);
        searchQuery.addAggregation(todayOrder);
        searchQuery.addAggregation(weekOrder);
        searchQuery.addAggregation(monthOrder);
        searchQuery.addAggregation(GoodComment);
        searchQuery.addAggregation(middleComment);
        searchQuery.addAggregation(badComment);
        Aggregations query = orderWorkEsBService.getAggregationsByQuery(searchQuery);

        Map<String, Aggregation> aggregationMap = query.getAsMap();

        Long allOrderCount =  ((ParsedFilter)aggregationMap.get("allOrder_filter")).getDocCount();
        Long todayOrderCount =  ((ParsedFilter)aggregationMap.get("todayOrder_filter")).getDocCount();
        Long weekOrderCount =  ((ParsedFilter)aggregationMap.get("weekOrder_filter")).getDocCount();
        Long monthOrderCount =  ((ParsedFilter)aggregationMap.get("monthOrder_filter")).getDocCount();
        Long goodCommentCount =  ((ParsedFilter)aggregationMap.get("goodComment_filter")).getDocCount();
        Long middleCommentCount =  ((ParsedFilter)aggregationMap.get("middleComment_filter")).getDocCount();
        Long badCommentCountCount =  ((ParsedFilter)aggregationMap.get("badComment_filter")).getDocCount();

        FcOrderCount fcOrderCount = new FcOrderCount();
        fcOrderCount.setTotalCount(allOrderCount);
        fcOrderCount.setTodayCount(todayOrderCount);
        fcOrderCount.setWeekCount(weekOrderCount);
        fcOrderCount.setMonthCount(monthOrderCount);
        fcOrderCount.setGoodCount(goodCommentCount);
        fcOrderCount.setMiddleCount(middleCommentCount);
        fcOrderCount.setBadCount(badCommentCountCount);

        return ResponseUtil.responseSuccess(fcOrderCount,"成功");
    }
}
